package com.tianquan.miracle.postprocessor;

import com.tianquan.miracle.annotation.Autowired;
import com.tianquan.miracle.annotation.Qualifier;
import com.tianquan.miracle.util.MiracleUtils;

import java.lang.reflect.Field;

/**
 * @BelongsProject: uploaddemo
 * @BelongsPackage: com.tianquan.miracle.postprocessor
 * @Author: tianquan
 * @CreateTime: 2024-09-30  09:18
 * @Description: 解析@Autowired注解，自动注入bean
 * @Version: 1.0
 */
public class AutowiredBeanPostProcessor implements InjectBeanPostProcessor {

    public void inject(Object bean) {
        Class<?> aClass = bean.getClass();
        for (Field field : aClass.getDeclaredFields()) {
            Autowired autowired = field.getAnnotation(Autowired.class);
            if (autowired == null) continue;
            field.setAccessible(true);
            try {
                // 优先根据类型注入
                Class<?> fieldClass = field.getType();
                Object value = MiracleUtils.getBean(fieldClass);
                if (value == null) {
                    // 判断是否有Qualifier注解
                    Qualifier qualifier = field.getAnnotation(Qualifier.class);
                    if (qualifier == null) throw new RuntimeException("can not find bean is " + field.getName());
                    String beanName = MiracleUtils.createBeanName(fieldClass);
                    value = MiracleUtils.getBean(beanName);
                    if (value == null) throw new RuntimeException("can not find bean is " + field.getName());
                }
                // 注入
                field.set(bean, value);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

}
